//
//  WBOAuthViewController.swift
//  传智微博
//
//  Created by zuxi li on 2017/3/20.
//  Copyright © 2017年 lingtu. All rights reserved.
//

import UIKit
import SVProgressHUD

/// 通过 webView 加载新浪微博授权页面控制器
class WBOAuthViewController: UIViewController {

    fileprivate lazy var webView = UIWebView()
    
    override func loadView() {
        view = webView
        webView.scrollView.isScrollEnabled = false  // 取消滚动视图 新浪微博的服务器返回的页面默认是手机全屏
        view.backgroundColor = UIColor.white
        webView.delegate = self
        // 设置导航栏
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", fontSize: 16, target: self, action: #selector(close), isBackButton: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFill))
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        // 加载授权页面
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirectURL)"
        guard let url = URL(string: urlString)  else {
            return
        }
        let request = URLRequest(url: url)
        webView.loadRequest(request)

        
    }


    // MARK: - 监听方法
    @objc fileprivate func close() {
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    
    /// 自动填充，WebView的注入， 通过JS修改本地浏览器中缓存的页面内容
    /// 点击登录按钮，会执行submit() 将本地数据提交给服务器
    @objc private func autoFill() {
        // 准备JS
        let js = "document.getElementsByClassName('input_note')[0].innerText = \"\";"+"document.getElementById('passwd').value = 'lizuxi1312732739';"+"document.getElementById('userId').value = '15369302776';"
        // 让webView直行
        webView.stringByEvaluatingJavaScript(from: js)
    }
}

extension WBOAuthViewController: UIWebViewDelegate {
    
    /// webView将要加载请求
    ///
    /// - Parameters:
    ///   - webView: webView
    ///   - request: 要加载的请求
    ///   - navigationType: 导航类型
    /// - Returns: 是否加载 request
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //如果请求地址包含 https://baidu.com 不加载页面 否则加载页面
        // 从https://baidu.com 回调地址中查询字符串中查找 ‘code=’ 如果有授权成功 否则授权失败

        // request.url?.absoluteString.hasPrefix(WBRedirectURL)  返回Bool（true、false） 或者 nil
        if request.url?.absoluteString.hasPrefix(WBRedirectURL) == false {
            return true
        }
        print("加载请求 --- \(request.url?.absoluteURL)")
        
        // query 是url ？ 后面的部分
        print("加载请求 --- \(request.url?.query)")
        if request.url?.query?.hasPrefix("code=") == false {
            print("取消授权")
            close()
            return false
        }
        // 从query字符串中取出授权码，代码走到自出url中一定有查询字符串并且包含code
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        print("获取授权码 \(code)")
        // 使用授权码获取AccessToken
        WBNetworkManager.shared.loadAccessToken(code: code) { (isSuccess) in
            if !isSuccess {
                SVProgressHUD.showInfo(withStatus: "网络请求失败")
            } else {
                SVProgressHUD.showInfo(withStatus: "登录成功")
                // 跳转界面 通过通知， 发送登录成功消息
                // 发送通知 不关心有没有接听者
                NotificationCenter.default.post(
                    name: NSNotification.Name(rawValue: WBUserLoginSuccessedNotification),
                    object: nil)
                
                // 关闭窗口
                self.close()
            }
        }
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
